import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'
import { logger } from 'runjs/lib/common'

const isLoginPage = (path) => {
  return path && path.indexOf('/login') >= 0
}

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  store.dispatch('tabs/updateRoute', to)
  // 处理三级页面缓存
  if (to.matched && to.matched.length > 2) {
    for (let i = 0; i < to.matched.length; i++) {
      const element = to.matched[i]
      if (element?.meta?.isBlank) {
        to.matched.splice(i, 1)
      }
    }
  }

  NProgress.start()

  document.title = getPageTitle(to.meta.title)
  const token = getToken();
  if (!token) {
    if (isLoginPage(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
      return
    }
    const hasGetUserInfo = store.getters.name
    if (hasGetUserInfo) {
      next()
    } else {
      try {
        // await store.dispatch('user/getInfo')
        // next()
        // 当字段isAddRoutes为false，重新dispatch getInfo，达到重新添加动态路由
        if (!store.state.user.isAddRoutes) {
          await store.dispatch('user/getInfo')
          next({ ...to, replace: true })
        } else {
          next()
        }
      } catch (error) {
        logger.error(error)
        await store.dispatch('user/resetToken')
        // Message.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
